package com.tarena.lbs.article.web.dao.repository;

import com.alibaba.fastjson2.JSON;
import com.sun.corba.se.spi.ior.IdentifiableFactory;
import com.tarena.lbs.pojo.content.entity.ActionSearchEntity;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.collapse.CollapseBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Repository
@Slf4j
public class ActionRepository {
    @Autowired
    private RestHighLevelClient client;

    public List<ActionSearchEntity> getActionAticles(Integer behavior, Integer userId) {
        //1.查询代码 使用RestHighLevelClient
        SearchRequest request=new SearchRequest("lbs_action");
        //2.关注一个bool查询条件 behavior字段等于 入参behavior behaveUserId字段等于入参 userId
        SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        query.must(QueryBuilders.termQuery("behavior",behavior));
        query.must(QueryBuilders.termQuery("behaviorUserId",userId));
        sourceBuilder.query(query);
        //3.查询到的数据 同一个用户给同一篇文章 点了多次赞 多条用户行为记录,articleId相同 去重
        sourceBuilder.collapse(new CollapseBuilder("articleId"));
        request.source(sourceBuilder);
        List<ActionSearchEntity> entities=null;
        //4.发起请求 获取响应
        try{
            SearchHit[] hits = client.search(request, RequestOptions.DEFAULT).getHits().getHits();
            if (hits!=null&&hits.length>0){
                entities= Arrays.stream(hits).map(hit->{
                    return JSON.parseObject(hit.getSourceAsString(),ActionSearchEntity.class);
                }).collect(Collectors.toList());
            }
        }catch (Exception e){
            log.error("查询用户行为相关的文章列表失败",e);
        }
        return entities;//每一个文章缺少一个封面图片.
    }
}
